from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from catalogue.models import Catalogue, Foods
from catalogue.serializers import CatalogueSerializer, FoodsSerializer
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.views import APIView
from django.http import Http404


@api_view(['GET', 'POST'])
@permission_classes([AllowAny])
def foods_list(request):
    if request.method == 'GET':
        cat = Catalogue.objects.all()
        serializer = CatalogueSerializer(cat, many=True)
        return Response(serializer.data)


class FoodsView(APIView):
    permission_classes = [AllowAny]

    def get_object(self, pk):
        """获取单个对象"""
        try:
            # pk 即主键，默认状态下就是 id
            return Catalogue.objects.get(pk=pk)
        except:
            raise Http404

    def post(self, request):
        params = request.data
        pk = params.get("pk", None)
        if not pk:
            return Response({"error": "缺少参数"}, status=status.HTTP_400_BAD_REQUEST)
        try:
            catalogue = self.get_object(pk)
            serializer = FoodsSerializer(catalogue.types.all(), many=True)
            return Response(serializer.data)
        except catalogue.DoesNotExist:
            return Response({"error": "类型查询失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

